<template>
  <div class="role">
    <PageSearch :search-form-config="searchFormConfig"></PageSearch>
    <PageContent
      :content-table-config="contentTableConfig"
      :prop-list="propList"
      page-name="role"
      @newBtnClick="handleNewData"
      @editBtnClick="handleEditData"
    ></PageContent>
    <PageModal
      ref="pageModalRef"
      :modal-config="modalConfig"
      page-name="role"
      :modal-info="modalInfo"
      :other-info="otherInfo"
    >
      <div class="tree">
        <!-- el-tree 树形数据展示 -->
        <el-tree
          ref="treeRef"
          :data="treeData"
          node-key="id"
          show-checkbox
          :props="{ children: 'children', label: 'name' }"
          @check="handleCheckChange"
        >
        </el-tree>
      </div>
    </PageModal>
  </div>
</template>

<script lang="ts" setup>
import { useInitialStore } from '@/store'

import PageContent from '@/components/PageContent/PageContent.vue'
import PageSearch from '@/components/PageSearch/PageSearch.vue'
import PageModal from '@/components/PageModal/PageModal.vue'

import { contentTableConfig, propList } from './config/content.config'
import { searchFormConfig } from './config/search.config'
import { modalConfig } from './config/modal.config'

import { usePageModal } from '@/hooks/usePageModal'
import { menuMapLeafKeys } from '@/utils/mapMenus'

import type { ElTree } from 'element-plus'

// el-tree数据 页面初始化就请求下来然后渲染到 pageModal组件里面的
const treeData = computed(() => useInitialStore().entireMenu) // 防止第一次没拿到数据 加一个计算属性

// 这个是树形选框的 数据回显函数
const treeRef = ref<InstanceType<typeof ElTree>>()
const editCallback = (item: any) => {
  const leafKeys = menuMapLeafKeys(item.menuList)
  // 因为这里可能会获取不到值 用nextTick
  nextTick(() => treeRef.value?.setCheckedKeys(leafKeys))
}

// 调用hooks函数 注意解构顺序 数组的要顺序对应上
const [modalInfo, pageModalRef, handleEditData, handleNewData] = usePageModal(
  undefined,
  editCallback
)

// 传入一些数据 这是el-tree选择的数据 modal框下面的树形选数据的
const otherInfo = ref({})
// el-tree带的事件方法 data整个绑定的对象（treeData） data2 选中的数据
const handleCheckChange = (data: any, data2: any) => {
  const checkedKeys = data2.checkedKeys
  const halfCheckedKeys = data2.halfCheckedKeys
  const menuList = [...checkedKeys, ...halfCheckedKeys]
  otherInfo.value = { menuList }
}
</script>

<style scoped lang="less">
.tree {
  margin-left: 60px;
}
</style>
